//
//  ARAddPhotoSingleModel.m
//  AwesomeRecorder
//
//  Created by Xing on 2019/11/29.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "AddVideoSingleModel.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "UIImage+Extension.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface AddVideoSingleModel()
<UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
TZImagePickerControllerDelegate>

@property(nonatomic, copy) void(^didAddVideoCompleteBlock)(PickerVideo *videoObject);

@end

@implementation AddVideoSingleModel

- (instancetype)sharedInstance {
    
    return [[self class] sharedInstance];
}

+ (instancetype)sharedInstance {
    
    static dispatch_once_t once;
    static id __singleton__;
    dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; });
    return __singleton__;
}

/**
 添加视频
 
 @param targetVC 目标VC
 @param complete 回调
 */
- (void) showAddMultiPhotoWinWithTargetVC:(UIViewController *)targetVC
                                 complete:(void(^)(PickerVideo *))complete {
    
    self.didAddVideoCompleteBlock = complete;
    
    WEAKSELF
    [Utils showAlertWithTitle:LocalStr(@"Getting Photos") content:nil targetVC:targetVC dismissBlock:^(NSInteger index) {
        if (index == 2) {
            [weakSelf pictureFromAlbumWithTargetVC:targetVC];
        } else if (index == 1){
            [weakSelf pictureFromCameraWithTargetVC:targetVC];
        }
    } cancelButton:LocalStr(@"Cancel") otherButtons:@[LocalStr(@"Shot"),LocalStr(@"Album")]];
}


- (void)pictureFromAlbumWithTargetVC:(UIViewController *)targetVC {
    
    PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
    
    if (author == PHAuthorizationStatusRestricted || author == PHAuthorizationStatusDenied) {
        
        [Utils showAlertWithTitle:LocalStr(@"Unable to access the album") content:LocalStr(@"Open Settings-Privacy-Photos for Setting") targetVC:targetVC dismissBlock:^(NSInteger index) {
            if (index == 0) {
                
                NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : @NO};
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:options completionHandler:^(BOOL success) {
                    if (success) {
                        NSLog(@"success");
                    }
                }];
            }
        } cancelButton:LocalStr(@"To Setting") otherButtons:@[LocalStr(@"Cancel")]];
        return;
        
    } else if (author == PHAuthorizationStatusAuthorized) {
        
        [self toImagePickerViewControllerWhenAuthorized:targetVC];
        
    } else if (author == PHAuthorizationStatusNotDetermined) {
        
        WEAKSELF
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                [weakSelf toImagePickerViewControllerWhenAuthorized:targetVC];
            }
        }];
    }
}

- (void)pictureFromCameraWithTargetVC:(UIViewController *)targetVC {
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        AVAuthorizationStatus author = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (author == AVAuthorizationStatusRestricted || author == AVAuthorizationStatusDenied) {
            
            [Utils showAlertWithTitle:LocalStr(@"Unable to access the album") content:LocalStr(@"Open Settings-Privacy-Photos for Setting") targetVC:targetVC dismissBlock:^(NSInteger index) {
                if (index == 0) {
                    NSDictionary *options = @{UIApplicationOpenURLOptionUniversalLinksOnly : @NO};
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:options completionHandler:^(BOOL success) {
                        if (success) {
                            NSLog(@"success");
                        }
                    }];
                }
            } cancelButton:LocalStr(@"To Setting") otherButtons:@[LocalStr(@"Cancel")]];
            return;
            
        } else if (author == AVAuthorizationStatusAuthorized) {
            
            [self toCameraViewControllerWhenAuthorized:targetVC];
            
        } else if (author == AVAuthorizationStatusNotDetermined) {
            
            WEAKSELF
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    [weakSelf toCameraViewControllerWhenAuthorized:targetVC];
                }
            }];
        }
        
    } else {
        
        [Utils showAlertViewWithTitle:LocalStr(@"No photo-taking function") content:nil buttonTitle:LocalStr(@"Sure") targetVC:targetVC];
    }
}

/**
 当权限得到授权时，跳转到拍照的VC
 */
- (void)toCameraViewControllerWhenAuthorized:(UIViewController *)targetVC {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    picker.videoMaximumDuration = 10.0;
    picker.modalPresentationStyle = UIModalPresentationOverFullScreen;
    
    [targetVC presentViewController:picker
                           animated:YES
                         completion:nil];
}

/**
 当权限得到授权时，跳转到选取相册的VC
 */
- (void)toImagePickerViewControllerWhenAuthorized:(UIViewController *)targetVC {
    
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePicker.allowTakePicture = NO;
    imagePicker.allowPickingImage = NO;
    imagePicker.allowTakeVideo = YES;
    imagePicker.timeout = 10;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [targetVC presentViewController:imagePicker
                               animated:YES
                             completion:nil];
    });
}

#pragma mark -
#pragma mark UIImagePicker delegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    NSURL *url =  [info objectForKey:UIImagePickerControllerMediaURL];
    
    if (!url || ![mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        return;
    }
    
    UIImage *image = [Utils getVideoPreviewImage:url.path];
    
    PickerVideo *obj = [PickerVideo new];
    obj.coverImage = image;
    obj.fileURL = url;
    
    if (self.didAddVideoCompleteBlock) {
        self.didAddVideoCompleteBlock(obj);
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
//    WEAKSELF
//    __block NSString *localIdentifier = nil;
//    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//        PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
//        localIdentifier = request.placeholderForCreatedAsset.localIdentifier;
//        request.creationDate = [NSDate date];
//    } completionHandler:^(BOOL success, NSError *error) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (success) {
//                PHAsset *asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil] firstObject];
//                [weakSelf didGetPHAssert:asset];
//            } else if (error) {
//                NSLog(@"保存视频出错:%@",error.localizedDescription);
//            }
//        });
//    }];
    
}
//- (void)didGetPHAssert:(PHAsset *)asset {
//
//    WEAKSELF
//    [[TZImageManager manager] getPhotoWithAsset:asset photoWidth:kScreenWidth completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
//
//        if (!isDegraded) {
//            [weakSelf finishPickerAssert:asset image:photo];
//        }
//    }];
//}
//
//- (void)finishPickerAssert:(PHAsset *)asset image:(UIImage *)image {
//
//
//}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark TZImagePickerControllerDelegate

//- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker __attribute__((deprecated("Use -tz_imagePickerControllerDidCancel:.")));
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    //do nothing
}

// If user picking a video, this callback will be called.
// 如果用户选择了一个视频，下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    
    if (coverImage && asset) {
        
        WEAKSELF
        //PHAssetResource * resource = [[PHAssetResource assetResourcesForAsset: asset] firstObject];
        
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
           
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:asset
              options:options
        resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            // asset 类型为 AVURLAsset  为此资源的fileURL
            // <AVURLAsset: 0x283386e60, URL = file:///var/mobile/Media/DCIM/100APPLE/IMG_0049.MOV>
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            
            PickerVideo *obj = [PickerVideo new];
            obj.fileURL = urlAsset.URL;
            obj.coverImage = coverImage;
            
            if (weakSelf.didAddVideoCompleteBlock) {
                weakSelf.didAddVideoCompleteBlock(obj);
            }
        }];
    }
}

@end
